package de.esk.fraunhofer.activity.Ladefahrplan;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ContentResolver;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;
import de.esk.fraunhofer.ECar;
import de.esk.fraunhofer.Einstellungen;
import de.esk.fraunhofer.MegTyp;
import de.esk.fraunhofer.R;
import de.esk.fraunhofer.ECM_DatenbankOperation.Query.Query_LFP;
import de.esk.fraunhofer.XMLAnalyser.XML_LFPItem;
import de.esk.fraunhofer.bluetoothlayer.BlueToothClient;
import de.esk.fraunhofer.bluetoothlayer.DeviceListActivity;

public class Ladefahrplan extends Activity implements MegTyp{
	//debug
    public static final boolean D=Einstellungen.Debug;
    private static final String TAG = "Ladefahrplan";
    public static final boolean iD=Einstellungen.iDebug;
    //SQLite
	private ContentResolver contentResolver;
	//private Uri mUri=Battery_STATUS_TABLE.CONTENT_URI;
    
	// Layout Views
    private TextView mTitle;
    // Name of the connected device
    private String mConnectedDeviceName = null;
    
	//Handler
	private final Handler _Handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
        	switch(msg.what){
        	case MESSAGE_XMLOBJ: 
        		if(msg.obj instanceof XML_LFPItem){//filter          			
        			        		
        			XML_LFPItem xmlLFP=(XML_LFPItem)msg.obj;  
        			if(D) Log.e(TAG,"LFP received xml object.");	
        			
        		}
        		
        		break;
            
        	case MESSAGE_STATE_CHANGE:
                
        		if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                
        		switch (msg.arg1) {                
        		case BlueToothClient.STATE_CONNECTED:                
                    mTitle.setText(R.string.title_connected_to);
                    mTitle.append(mConnectedDeviceName);
                    break;
                case BlueToothClient.STATE_CONNECTING:
                    mTitle.setText(R.string.title_connecting);
                    break;
                case BlueToothClient.STATE_COORDINATE:
                case BlueToothClient.STATE_NONE:
                    mTitle.setText(R.string.title_not_connected);
                    break;
                }
                break;	                
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to "
                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
        	}
        }		
	};
	//************************************Activity life cycle*********************************************
	@Override
	public void onCreate(Bundle savedInstanceState){
    	if(D) Log.e(TAG,"+++ On Created +++");
		super.onCreate(savedInstanceState);
		
		// Set up the window layout
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        //TODO design layout
        this.setContentView(R.layout.ladefahrplan_layout);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
        
        // Set up the custom title
        mTitle = (TextView) findViewById(R.id.title_left_text);
        mTitle.setText(R.string.app_name);
        mTitle = (TextView) findViewById(R.id.title_right_text);
		
        // Get local Bluetooth adapter
        ECar.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (ECar.mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
	}
	
	@Override
	public void onStart(){
		super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");
        
        // If BT is not on, request that it be enabled.
        if (!ECar.mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, ECar.REQUEST_ENABLE_BT);
        } else {
            if(ECar.mBluetoothClient==null) setupBlueToothClient();        }	
		
        //load data from SQLLite
		
		//retrieve data

		//set GUI

	}
	
	@Override
	public void onResume(){
		super.onResume();
		//set handler for incoming data switch.
		ECar.mBluetoothClient.setmHandler(_Handler);
		mTitle.setText(ECar.ConnectionStatus);
        if(D) Log.e(TAG, "+ ON RESUME +");        
	}
	
	// For date Storage it is better to implement the code here.
	@Override
	public void onPause(){
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
        
        //save ConncetionStatus
        ECar.ConnectionStatus=mTitle.getText();      
        
		//save data to SQLLite
	}
	
    @Override
    public void onStop() {        
    	super.onStop();     
        if(D) Log.e(TAG, "-- ON STOP --");        
    }

    @Override
    public void onDestroy() {    	
        super.onDestroy();             
        if(D) Log.e(TAG, "--- ON DESTROY ---");        
    }
    //**********************************************************************************************
    @Override
    public boolean onPrepareOptionsMenu(Menu menu){
    	super.onPrepareOptionsMenu(menu); 
        MenuInflater inflater = getMenuInflater();
        menu.clear();
        if(ECar.mBluetoothClient.getState()==3)
        	inflater.inflate(R.menu.ecar_connected, menu);
        else
        	if(iD) {
        		inflater.inflate(R.menu.ecar_connected, menu);
        	}
        	else{
        		inflater.inflate(R.menu.option_menu, menu);
        	}
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        
        case R.id.scan:
            // Launch the DeviceListActivity to see devices and do scan
            Intent serverIntent = new Intent(this, DeviceListActivity.class);            
            startActivityForResult(serverIntent, ECar.REQUEST_CONNECT_DEVICE);            
            return true;
        
        case R.id.discoverable:
            // Ensure this device is discoverable by others            
        	ensureDiscoverable();            
        	return true;
        
        case R.id.Query:
        	sendtoECM(new Query_LFP().Query_LFP_ALL());
        	return true;
        }
        return false;    
    }
    
    private void ensureDiscoverable() {
        
    	if(D) Log.d(TAG, "ensure discoverable");        
        if (ECar.mBluetoothAdapter.getScanMode() !=            
        	BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            
        	Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);            
        	discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);            
        	startActivity(discoverableIntent);        
        }    
    }

    private void setupBlueToothClient(){
        // Initialize the BluetoothClient to perform bluetooth connections
        ECar.mBluetoothClient = new BlueToothClient(_Handler);
    }
    
    @Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(D) Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode) {
        case ECar.REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                // Get the device MAC address
                String address = data.getExtras()
                                     .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                // Get the BLuetoothDevice object
                BluetoothDevice device = ECar.mBluetoothAdapter.getRemoteDevice(address);
                // Attempt to connect to the device
                ECar.mBluetoothClient.connect(device);
            }
            break;
        case ECar.REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session
                setupBlueToothClient();
            } else {
                // User did not enable Bluetooth or an error occured
            	if(D) Log.d(TAG, "BT not enabled");
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
    
    /**
     * Sends a message to ECM.
     * @param message  A string of text to send.
     */    
    private void sendtoECM(String message) {
    	
        // Check that we're actually connected before trying anything
        if (ECar.mBluetoothClient.getState() == BlueToothClient.STATE_CONNECTED) {            
        	// Check that there's actually something to send
            if (message.length() > 0) {
                // Get the message bytes and tell the BluetoothChatService to write
                byte[] send = message.getBytes();                
                ECar.mBluetoothClient.write(send);
            }                        
        }
        else{        	
        	if(D) Log.e(TAG,"sendquery blocked not connected");            
        	Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();            
            return;
        }        
    }
}